# -*- coding: utf-8 -*-
"""
api_v1是旧版本， 跟旧的url、输入、输出一致。 不使用blueprint, 而是@current_app.route
api_v2是新版本， url、输入、输出可能会变，会引入blueprint/ api_ok/ api_error等。

先写完旧版本，再来拼凑新版本。
"""
from . import support
from . import order
from . import hotel
from . import plan
from . import product
from . import product_h5
from . import user


from flask import request, current_app, session
from app.data_structures import get_version_from_user_agent, NoAppVersion, FancyDict
from app.models import User
from app.third_party_api import btapi
from flask.ext.login import LoginManager, UserMixin, current_user, login_user, logout_user


@current_app.before_request
def before_request():
    """
    预处理用@before_request来解决就行了，用middleware是大材小用。middleware的优势在于：1.用于多个项目 2.方便的启用禁用

    此处包括旧系统中的：
    BreadtripSessionMiddleware
    GlobalRequestMiddleware
    """
    request.breadtrip = FancyDict({
                            "is_breadtrip": True,
                            "is_aoyouji": False,
                            "is_api": False,
                            "is_thailand": False,
                            "version": NoAppVersion(),
                            "is_mobile": False,
                            "is_mobile_ios": False,
                            "device_name": '',
                            "is_vacation": False
                        })

    user_agent = request.headers.get('HTTP_USER_AGENT', '').lower()
    request.breadtrip.update({'user_agent': user_agent})
    if any(x in user_agent for x in ('iphone', 'itouch', 'ipod', 'ipad')):
        request.breadtrip.is_mobile = True
        request.breadtrip.is_mobile_ios = True
    if 'android' in user_agent:
        request.breadtrip.is_mobile = True
    if 'thailand' in user_agent:
        request.breadtrip.is_thailand = True

    if 'BREADTRIP' in user_agent.upper():
        request.breadtrip.version = get_version_from_user_agent(user_agent)

    if 'vacation' in user_agent.lower():
        request.breadtrip.is_vacation = True

    request.user = current_user
    # print 'current_user', current_user, dir(current_user)
    # print 'session', session


@current_app.login_manager.user_loader
def load_user(id):
    # 暂时只在session中存id，如果存其它信息的话，有可能面包旅行那边用户信息变了，这边还是旧的
    from app.models import User
    _user = User()
    _user.id = id
    return _user
